package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author qinluoyu
 *
 */
@Service
public class WmUserserviceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    /**
     * 登录功能的实现
     *
     * @return
     */
    @Override
    public ResponseResult login(WmLoginDto dto) {
        //1.获取到前端传来的账号密码
        String name = dto.getName();
        String password = dto.getPassword();
        //2.判断账号密码是否为空
        if (StringUtils.isBlank(name) || StringUtils.isBlank(password)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //3.账号密码都不为空，去数据库查询，看一下是否命中
        LambdaQueryWrapper<WmUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmUser::getName, name);
        WmUser wmUser = getOne(wrapper);
        //4.看一下数据库是不是存有这个账号
        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "账号不存在");
        }
        //5.比较密码，先加盐，再md5加密
        String AfterPassword = password + wmUser.getSalt();
        String FinalPassword = DigestUtils.md5DigestAsHex(AfterPassword.getBytes());

        if (!FinalPassword.equals(wmUser.getPassword())) {
            //6.密码错误，登录失败
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //7.密码正确，登录成功,给前端传一个hashMap，包括登录成功的用户信息和一个登录校验的token
        Map<String, Object> result = new HashMap<>();
        wmUser.setSalt("");
        wmUser.setPassword("");
        //以id来生成token，方便后面解析获取操作者的id
        String token = AppJwtUtil.getToken((long) wmUser.getId());
        result.put("token", token);
        result.put("user", wmUser);

        //threadlocal有大问题
        /*WmThreadLocalUtil.setUser(wmUser);*/


        return ResponseResult.okResult(result);

    }
}
